package com.jack.lease.web.admin.controller.apartment;

import com.jack.lease.common.result.Result;
import com.jack.lease.web.admin.service.FileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


@Slf4j
@Tag(name = "文件管理")
@RequestMapping("/admin/file")
@RestController
public class FileUploadController {

    @Resource
    private FileService fileService;

    @Operation(summary = "上传文件")
    @PostMapping("upload")
    public Result<String> upload(@RequestParam MultipartFile file) {
        try {
            byte[] bytes = file.getBytes();
            String originalFilename = file.getOriginalFilename();
            String url = fileService.upload(bytes, originalFilename);
            return Result.ok(url);
        } catch (IOException e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new RuntimeException("上传失败");
        }
    }

    @GetMapping("/getImage/{id}/{fileName}")
    public ResponseEntity<Object> getImage(@PathVariable("id") Long id,
                                           @PathVariable("fileName") String fileName) {

        return fileService.getImage(id, fileName);
    }

}
